package com.zaofan.mobile.controller;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.zaofan.bean.DynamicDTO;
import com.zaofan.exception.ServiceException;
import com.zaofan.service.TopicService;
import com.zaofan.utils.JsonUtils;
import com.zaofan.utils.WebUtils;

/**
 *
 */
@WebServlet("/mobile/topicReply")
public class TopicReplyController extends HttpServlet {

	private static final long serialVersionUID = 5884947841079014459L;
	private TopicService topicService = new TopicService();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		reply(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	/**
	 * 评论话题
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void reply(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {

			DynamicDTO dto;
			if (ServletFileUpload.isMultipartContent(request)) {
				dto = dealAppAddDynamic(request);
			} else {
				dto = WebUtils.write2bean(request, DynamicDTO.class);
			}
			topicService.replyTopic(dto);
			JsonUtils.writeSuccessJson("发布成功", "", response);
			return;
		} catch (ServiceException e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson(e.getMessage(), response);
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("发布失败", response);
		}
		JsonUtils.writeBeanFailJson("发布失败!!", response);
	}

	private DynamicDTO dealAppAddDynamic(HttpServletRequest request) {
		DynamicDTO dto = new DynamicDTO();
		String images = "";
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");
		String random = new Random().nextInt() + "";
		try {
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					String value = item.getString();
					String key = item.getFieldName();
					BeanUtils.setProperty(dto, key, value);
					System.out.println(key + " = " + value);
				} else {
					InputStream in = item.getInputStream();
					String path = WebUtils.makeDir(getServletContext().getRealPath("/user_image"),
							new StringBuilder(String.valueOf(random)).toString()) + "/" + WebUtils.getUUID() + "_"
							+ random + item.getName().substring(item.getName().lastIndexOf("."));
					FileOutputStream out = new FileOutputStream(
							getServletContext().getRealPath("/user_image") + "/" + path);
					BufferedOutputStream bos = new BufferedOutputStream(out);
					int len = 0;
					byte[] buff = new byte[1024];
					while ((len = in.read(buff)) != -1) {
						bos.write(buff, 0, len);
					}
					bos.close();
					images += "/user_image/" + path + ",";
				}
			}
			if (images.length() > 0) {
				images = images.substring(0, images.length() - 1);
			}
			dto.setImage(images);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dto;
	}

}
